<!-- 用户注册申请、引导下载软件 -->

<template>
  <div class="home">
    <div class="applyAndDown_idex1">
      <div class="titleTop">金帝商城</div>
      <div class="title">支付宝红包券 抢百种福利</div>
      <div class="title2">新用户审核通过率高达92.58%</div>
      <van-image width="100%" height="39" :src="imageUrl" />
      <div class="applyAndDown_idex2">
        <div class="money">最高可领(元)</div>
        <div class="dinmoney">20,000</div>
        <div class="interest">享品牌数码折扣</div>
        <van-cell-group class="imgCodeGroup" style="margin-top: 40px">
          <van-field
            class="imgCode"
            v-model="formData.telPhoneNum"
            :formatter="formatter"
            required
            placeholder="请输入您的手机号"
          />
        </van-cell-group>
        <van-cell-group class="imgCodeGroup">
          <van-field
            class="imgCode"
            v-model="formData.telPhoneMessage"
            type="number"
            center
            clearable
            placeholder="请输入短信验证码"
          >
            <template #button>
              <van-button
                v-if="sendCodeClicked"
                size="small"
                type="primary"
                @click="sendVerificationCode"
                >获取验证码</van-button
              >
              <span v-if="!sendCodeClicked">{{ countdown }}秒后重新获取</span>
            </template>
          </van-field>
        </van-cell-group>
        <div style="margin: 16px">
          <van-button
            class="submitBtn"
            block
            native-type="submit"
            @click="onsubmitViewCredit"
            >查看额度</van-button
          >
        </div>
        <submit-dialog ref="dialogRef"></submit-dialog>
        <div class="loginAgreement">
          <van-checkbox
            shape="square"
            v-model="formData.boxChecked"
            icon-size="14px"
          ></van-checkbox>
          <span style="margin-left: 8px">我已阅读并同意</span
          ><a href="/userAgreement" style="color: #797d89">《软件注册协议》</a
          ><a href="/privacyAgreement" style="color: #797d89">《隐私协议》</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { sendCode, submit } from "@/api/user";
import { showToast } from "vant";
import myImage from "@/assets/line.png";
import { useRoute, useRouter } from "vue-router";
import submitDialog from "./moduels/submitDialog.vue";
import { ref } from "vue";
import { mockApi } from "@/utils/util";

const dialogRef = ref(null);

export default {
  name: "applyAndDown",
  components: { submitDialog },
  data() {
    return {
      channel: "",
      imageUrl: myImage,
      formData: {
        telPhoneNum: "",
        telPhoneMessage: "",
        boxChecked: false,
      },
      sendCodeClicked: true,
      timer: undefined,
      countdown: 60,
    };
  },
  mounted() {
    const route = useRoute();
    // console.log(route);
    const { channel } = route.query;
    this.channel = channel as string;
    if (!channel) {
      showToast("没有渠道商来源！");
    }
  },
  watch: {
    countdown(val) {
      if (val <= 0) {
        this.sendCodeClicked = true;
        clearInterval(this.timer);
        this.countdown = 60;
      }
    },
  },
  methods: {
    onsubmitViewCredit() {
      this.$refs.dialogRef?.open(this.formData.telPhoneNum, this.channel);
    },
    formatter(value) {
      // 只保留数字，并限制长度为 11
      return value.replace(/\D/g, "").slice(0, 11);
    },
    // 判断当前页面是在微信浏览器中打开还是在移动端本地浏览器中打开
    checkBrowser() {
      const ua = navigator.userAgent.toLowerCase();

      if (ua.indexOf("micromessenger") !== -1) {
        return "WeChat Browser"; // 微信浏览器
      } else if (ua.indexOf("mobile") !== -1) {
        return "Mobile Browser"; // 移动端本地浏览器
      } else {
        return "Desktop Browser"; // 桌面浏览器
      }
    },
    async sendVerificationCode() {
      const { telPhoneNum } = this.formData;
      if (telPhoneNum) {
        try {
          await sendCode({ phone: telPhoneNum });
          console.log("request1");
          showToast("验证码已发送，10分钟内有效");
          // 设置定时器
          this.timer = setInterval(() => {
            this.countdown--;
          }, 1000);
          this.sendCodeClicked = false;
        } catch (error) {
          console.log(error, "request2");
          this.countdown = 0;
          this.sendCodeClicked = true;
        }
      } else {
        showToast("请先填写手机号");
      }
    },
    // 判断设备类型调用app下载
    detectDevice() {
      const userAgent = navigator.userAgent;
      let deviceType = "Unknown";
      if (/android/i.test(userAgent)) {
        deviceType = "Android";
      } else if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
        deviceType = "iOS";
      } else if (/Windows|Macintosh|Linux/.test(userAgent)) {
        deviceType = "Desktop";
      } else {
        deviceType = "Unknown";
      }
      const downLoadUrl =
        deviceType === "Android"
          ? "https://jd.h5.jirong.cloud/download/app/jindi.apk"
          : deviceType === "iOS"
          ? "itms-services://?action=download-manifest&url=https://jd.h5.jirong.cloud/jindi.plist"
          : "";
      if (downLoadUrl) window.location.href = downLoadUrl;
    },
    onsubmit() {
      const { telPhoneNum, telPhoneMessage, boxChecked } = this.formData;
      if (telPhoneNum) {
        if (telPhoneMessage) {
          if (boxChecked) {
            submit({
              channelCode: this.$route.query.code,
              phone: telPhoneNum,
              code: telPhoneMessage,
              grantType: "phone",
            })
              .then(() => {
                showToast("注册成功");
                this.detectDevice();
                // // 设置定时器
                // this.timer = setInterval(() => {
                //   this.countdown--;
                // }, 1000);
                // this.sendCodeClicked = false;
              })
              .catch((error) => {
                // this.countdown = 0;
                // this.sendCodeClicked = true;
              });
          } else {
            showToast("请先同意协议");
          }
        } else {
          showToast("请先填写验证码");
        }
      } else {
        showToast("请先填写手机号");
      }
    },
  },
  created() {
    const browserType = this.checkBrowser();
    if (browserType === "WeChat Browser") {
      // 微信打开落地页跳转引导图
      useRouter().push("/guidePage");
    }
    console.log(`当前页面在 ${browserType} 中打开`);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
};
</script>

<style lang="scss" scoped>
.applyAndDown_idex1 {
  padding-top: 20px;
  width: 100%;
  height: 330px;
  background-size: cover;
  background-image: url("../assets/bg1.png");
  .titleTop {
    margin-left: 15px;
    height: 24px;
    font-family: FZH;
    font-weight: 400;
    font-size: 20px;
    color: #fff;
    line-height: 33px;
  }
  .title {
    margin-top: 37px;
    text-align: center;
    width: 100%;
    height: 34px;
    // font-family: FZH;
    font-weight: 400;
    font-size: 26px;
    color: #fff;
    line-height: 34px;
  }
  .title2 {
    width: 100%;
    height: 17px;
    font-weight: 500;
    font-size: 12px;
    text-align: center;
    color: #fff;
    line-height: 14px;
    margin-bottom: 18px;
  }
  .applyAndDown_idex2 {
    margin-top: 16px;
    padding: 22px 22px 0;
    width: 100%;
    height: 455px;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-image: url("../assets/bg2.png");
    .money {
      margin: 34px auto 16px;
      width: 100%;
      height: 23px;
      font-family: PingFang SC;
      text-align: center;
      font-weight: 800;
      font-size: 17px;
      color: #333;
    }
    .dinmoney {
      width: 100%;
      height: 59px;
      font-family: DIN;
      font-weight: 700;
      font-size: 45px;
      color: #333;
      line-height: 49px;
      text-align: center;
    }
    .interest {
      text-align: center;
      width: 100%;
      height: 14px;
      font-family: PingFang SC;
      font-weight: 400;
      font-size: 10px;
      color: #333;
      margin-bottom: 25px;
    }
    .imgCodeGroup {
      margin: 14px 15px 0;
      text-align: center;
      background: #fff;
    }
    .submitBtn {
      background-color: #ff611c;
      border-radius: 4px;
      font-size: 17px;
      color: #fff;
      font-weight: bold;
    }
    .loginAgreement {
      display: flex;
      justify-content: center;
      font-size: 12px;
      align-items: center;
      color: #666;
    }
  }
}
</style>
